package com.start.form.engine.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.start.common.exceptions.StartBusException;
import com.start.form.engine.core.entity.StartFormConfig;
import com.start.form.engine.core.mapper.SysFormConfigMapper;
import com.start.form.engine.core.service.StartFormConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class StartFormConfigServiceImpl extends ServiceImpl<SysFormConfigMapper, StartFormConfig> implements StartFormConfigService {

    @Override
    public void createEntity(StartFormConfig entity) {
        if (StringUtils.isEmpty(entity.getTableName())) throw new StartBusException("数据表名不能为空");
        if (StringUtils.isEmpty(entity.getName())) throw new StartBusException("数据表中文名称不能为空");
        save(entity);
    }

    /**
     * 根据表单编码获取表单配置
     *
     * @param formCode
     * @return
     */
    @Override
    public StartFormConfig getOneByFormCode(String formCode) {
        LambdaQueryWrapper<StartFormConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StartFormConfig::getFormCode, formCode);
        return getOne(queryWrapper);
    }

    @Override
    public long getTableHistoryCount(String tableName) {
        LambdaQueryWrapper<StartFormConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StartFormConfig::getTableName, tableName);
        queryWrapper.gt(StartFormConfig::getTableVersion, 0);
        return count(queryWrapper);
    }
}
